import {
	defineStore
} from 'pinia';
import userApi from '@/ulm/api/user';
import {
	getToken,
	setToken,
	removeToken
} from '../utils/auth';

// 默认用户信息
const defaultUserInfo = {
	avatar: '', // 头像
	nickname: '', // 昵称
	gender: 0, // 性别
	mobile: '', // 手机号
};
const user = defineStore({
	id: 'user',
	state: () => ({
		userInfo: {
			...defaultUserInfo
		}, // 用户信息
		isLogin: !!getToken(), // 登录状态
	}),

	actions: {
		// 获取个人信息
		async getInfo() {
			const {
				error,
				data
			} = await userApi.profile();
			if (error !== 0) return;
			this.userInfo = data;
			return Promise.resolve(data);
		},


		// 设置token
		setToken(token = '') {
			if (token === '') {
				this.isLogin = false;
				removeToken();
			} else {
				this.isLogin = true;
				setToken(token)
			}
			return this.isLogin;
		},

		// 重置用户默认数据
		resetUserData() {
			this.setToken();
			// this.userInfo = clone(defaultUserInfo);
			this.userInfo = defaultUserInfo
		},
		// 登出
		async logout(force = false) {
			if (!force) {
				const {
					error
				} = await userApi.logout();
				if (error === 0) {
					this.resetUserData();
				}
			}
			if (force) {
				this.resetUserData();
			}

			return !this.isLogin;
		},
	},
});

export default user;